<?php
/**
 * Created by PhpStorm.
 * User: g
 * Date: 2017/5/3
 * Time: 11:13
 */

namespace app\front\controller;
use think\Request;

class Payform extends Home
{


    public function jk(){
//生成订单信息
        $interface = input("interface");
        $user = db("account_registration")->where("id",$this->userId)->find();
        $order = array();
        $order['orderno'] = 'No'.date("YmdHis").rand(10,100);
        $order['catid'] = 1;
        $order['lang'] = 'zh-cn';
        $order['username'] = $user['username'];
        $order['contact'] = $user['contact'];
        $order['mobile'] = $user['mobile'];
        $order['email'] = $user['email'];
        $order['amount'] = input('amount');
        $order['payment'] = $interface;
        $order['audit'] = 2;
        $order['onlinepay'] = 1;
        $order['success'] = 0;
        $order['createdate'] = date("YmdHis");
        $res = db("account_capital")->data($order)->insert();
        if($res){
            //生成订单成功，跳转支付页面
            $payment = db("pay_interface")->where("id",$interface)->find();
            $this->assign("payment",$payment);
            $request = Request::instance();
            //金控
            $params = array();
            $params["charset"] = "02";
            $params['version'] = "1.0";
         //   $params['merchantCert'] = "888057115732001";
            $params['signType'] = "RSA";
            $params['service'] = "DirectPayment";
            $params['offlineNotifyUrl'] = $request->domain().url("jkok");
            $params['requestId'] = $order['orderno'];
            $params['merchantId'] = $payment['merchantno'];
            $params['orderId'] = $order['orderno'];
            $params['orderTime'] = $order['createdate'];
            $params['totalAmount'] = floatval($order['amount'])*100;
            $params['currency'] = "CNY";
            $params["validUnit"] = "01";
            $params["validNum"] = "07";
            $params["pageReturnUrl"] = $request->domain().url("jkok");
            $params["merchantName"] = config("merchantName");
            $params["showUrl"] = $request->domain().url('front/payform/ok');
            $params["productName"] = config("productName");
            $params["productDesc"] = config("productDesc");
            ksort($params);
            $this->assign("paramData",arrToQuery($params,false));
            $sign = sign($params,"cert/jk/".$payment['merchantno'].".p12",config("certPass"));
            $this->assign("params",$params);
            $this->assign("sign",$sign['sign']);
            $this->assign("cert",$sign['cert']);

            return $this->fetch();
        }else{
            $this->error("入金操作失败，请重试！",url("front/personal/index"));
        }
    }

    public function jkok(){
        if(IS_POST) {
            $post = input("post.");
            $serverSign = $post["serverSign"];
            $serverCert = $post["serverCert"];
            //组装签字字符串
            $responseData = array();
            $responseData["acDate"] = $post['acDate'];
            $responseData["backParam"] = $post['backParam'];
            $responseData["bankAbbr"] = $post['bankAbbr'];
            $responseData["charset"] = $post['charset'];
            $responseData["fee"] = $post['fee'];
            $responseData["merchantId"] = $post['merchantId'];
            $responseData["orderId"] = $post['orderId'];
            $responseData["orderTime"] = $post['orderTime'];
            $responseData["payTime"] = $post['payTime'];
            $responseData["purchaserId"] = $post['purchaserId'];
            $responseData["returnCode"] = $post['returnCode'];
            $responseData["returnMessage"] = $post['returnMessage'];
            $responseData["service"] = $post['service'];
            $responseData["signType"] = $post['signType'];
            $responseData["status"] = $post['status'];
            $responseData["totalAmount"] = $post['totalAmount'];
            $responseData["tradeNo"] = $post['tradeNo'];
            $responseData["version"] = $post['version'];
            $signData = "";
            foreach ($responseData as $key => $value) {
                if ($value != '') {
                    $signData = $signData . $key . '=' . $value . '&';
                }
            }
            $verify = false;
            $rsignData = substr($signData, 0, strlen($signData) - 1);
            $verify = rsaVerify($rsignData, $serverSign, $serverCert);
            $order = db("account_capital")->where("orderno", $post['orderId'])->find();
            if ($verify && $post['status'] == "SUCCESS") {
                //更改订单状态
                $order['merchantno'] = $post["merchantId"];
                $order['ordernocard'] = $post["tradeNo"];
                $order['bank'] = $post['bankAbbr'];
                $order['success'] = 1;
                $res = db("account_capital")->where("id", $order['id'])->update($order);
                if ($res) {
                    $this->assign("record", $post);
                    return $this->fetch("jksuccess");
                } else {
                    $this->assign("record", $post);
                    return $this->fetch("jkserver");
                }
            } else {
                $order['merchantno'] = $post["merchantId"];
                $order['ordernocard'] = $post["tradeNo"];
                $order['success'] = 2;
                $res = db("account_capital")->where("id", $order['id'])->update($order);
                $this->assign("record", $post);
                return $this->fetch("jkfail");
            }
        }else{
            return $this->fetch("front/income/index");
        }

    }
    public function hxzf(){
        $interface = input("interface");
        $user = db("account_registration")->where("id",$this->userId)->find();
        $order = array();
        $order['orderno'] = 'No'.date("YmdHis").rand(10,100);
        $order['catid'] = 1;
        $order['lang'] = 'zh-cn';
        $order['username'] = $user['username'];
        $order['contact'] = $user['contact'];
        $order['mobile'] = $user['mobile'];
        $order['email'] = $user['email'];
        $order['amount'] = input('amount');
        $order['payment'] = $interface;
        $order['audit'] = 2;
        $order['onlinepay'] = 1;
        $order['success'] = 0;
        $order['createdate'] = date("YmdHis");
        $res = db("account_capital")->data($order)->insert();
        if($res){
            //生成订单成功，跳转支付页面
            $payment = db("pay_interface")->where("id",$interface)->find();
            $this->assign("payment",$payment);
            $request = Request::instance();
            $params = array();
            //环迅支付
            $params["Mer_code"] = $payment["merchantno"];
            $params["Billno"] = $order['orderno'];
            $params["Amount"] = number_format(floatval(input('amount')),2);
            $params['Date'] = date("Ymd");
            $params['Currency_Type'] = "156";
            $params['Gateway_Type'] = "01";
            $params['Lang'] = "GB";
            $params['Merchanturl'] = $request->domain().url('front/payform/ok');
            $params['FailUrl'] = $request->domain().url('front/payform/ok');
            $params["ErrorUrl"] = '';
            $params["Attach"] = date("Ymd");
            $params["DispAmount"] = "0.10";
            $params["OrderEncodeType"] = "5";
            $params["RetEncodeType"] = "17";
            $params["Rettype"] = "1";
            $params["ServerUrl"] = $request->domain().url('front/payform/ok');
            $signMD5 = md5("billno".$params['Billno']."currencytype".$params['Currency_Type']."amount".$params['Amount']."date".$params["Date"]."orderencodetype".$params['OrderEncodeType'].config("hxzfMer_Key"));
            //组织报文
            $body = "<body>".
                "<MerBillNo>".$params['Billno']."</MerBillNo>".
                "<Amount>".$params['Amount']."</Amount>".
                "<Date>".$params['Date']."</Date>".
                "<CurrencyType>".$params['Currency_Type']."</CurrencyType>".
                "<GatewayType>".$params['Gateway_Type']."</GatewayType>".
                "<Lang>".$params['Lang']."</Lang>".
                "<Merchanturl><![CDATA[".$params['Merchanturl']."]]></Merchanturl>".
                "<FailUrl><![CDATA[".$params['FailUrl']."]]></FailUrl>".
                "<Attach><![CDATA[".$params['Attach']."]]></Attach>".
                "<OrderEncodeType>".$params['OrderEncodeType']."</OrderEncodeType>".
                "<RetEncodeType>".$params['RetEncodeType']."</RetEncodeType>".
                "<RetType>".$params['Rettype']."</RetType>".
                "<ServerUrl><![CDATA[".$params['ServerUrl']."]]></ServerUrl>".
                "<BillEXP></BillEXP>".
                "<GoodsName>".config('productName')."</GoodsName>".
                "<IsCredit></IsCredit>".
                "<BankCode></BankCode>".
                "<ProductType></ProductType>".
                "</body>";
            $signature = md5($body.$params['Mer_code'].config("hxzfMer_Key"));
            $head = "<head>".
                "<Version>v1.0.0</Version>".
                "<MerCode>".$params['Mer_code']."</MerCode>".
                "<MerName>".config('merchantName')."</MerName>".
                "<Account>".config('hxAccount')."</Account>".
                "<MsgId>".date("YmdHis")."</MsgId>".
                "<ReqDate>".date("YmdHis")."</ReqDate>".
                "<Signature>".$signature."</Signature>".
                "</head>";
            $msg = "<Ips><GateWayReq>".$head.$body."</GateWayReq></Ips>";
            $this->assign("pGateWayReq",$msg);
          //  $this->assign("signMD5",strtolower($signMD5));
            return $this->fetch();
        }else{
            $this->error("入金操作失败，请重试！",url("front/personal/index"));
        }
    }

    public function kltok(){
        if(IS_POST) {
            $post = input('post.');
            $merchantId = $post["merchantId"];   //商户的id
            $version = $post['version'];         //版本的型号
            $language = $post['language'];       //语言
            $signType = $post['signType'];       //签名的种类
            $payType = $post['payType'];         //支付方式
            $issuerId = $post['issuerId'];       //发卡方的代码
            $mchtOrderId = $post['mchtOrderId']; //开联的商品的订单号
            $orderNo = $post['orderNo'];         //商户的订单号
            $orderDatetime = $post['orderDatetime'];//商户订单提交时间
            $orderAmount = $post['orderAmount'];    //商户订单的数量
            $payDatetime = $post['payDatetime'];    //支付完成时间
            $ext1 = $post['ext1'];                  //返回给商户的信息
            $ext2 = $post['ext2'];                  //返回给商户的信息
            $payResult = $post['payResult'];        //处理结果
            $signMsg = $post["signMsg"];            //签名字符串


            $bufSignSrc = "";                        //签名字符串的拼接
            if ($merchantId != "")
                $bufSignSrc = $bufSignSrc . "merchantId=" . $merchantId . "&";
            if ($version != "")
                $bufSignSrc = $bufSignSrc . "version=" . $version . "&";
            if ($language != "")
                $bufSignSrc = $bufSignSrc . "language=" . $language . "&";
            if ($signType != "")
                $bufSignSrc = $bufSignSrc . "signType=" . $signType . "&";
            if ($payType != "")
                $bufSignSrc = $bufSignSrc . "payType=" . $payType . "&";
            if ($issuerId != "")
                $bufSignSrc = $bufSignSrc . "issuerId=" . $issuerId . "&";
            if ($mchtOrderId != "")
                $bufSignSrc = $bufSignSrc . "mchtOrderId=" . $mchtOrderId . "&";
            if ($orderNo != "")
                $bufSignSrc = $bufSignSrc . "orderNo=" . $orderNo . "&";
            if ($orderDatetime != "")
                $bufSignSrc = $bufSignSrc . "orderDatetime=" . $orderDatetime . "&";
            if ($orderAmount != "")
                $bufSignSrc = $bufSignSrc . "orderAmount=" . $orderAmount . "&";
            if ($payDatetime != "")
                $bufSignSrc = $bufSignSrc . "payDatetime=" . $payDatetime . "&";
            if ($ext1 != "")
                $bufSignSrc = $bufSignSrc . "ext1=" . $ext1 . "&";
            if ($ext2 != "")
                $bufSignSrc = $bufSignSrc . "ext2=" . $ext2 . "&";
            if ($payResult != "")
                $bufSignSrc = $bufSignSrc . "payResult=" . $payResult;

            $public_key = file_get_contents("cert/klt/CSMTCert.cer");
            $params_sha1x16 = sha1($bufSignSrc, false);
            $isSuccess = openssl_verify($params_sha1x16, $signMsg, $public_key);
            $order = db("account_capital")->where("orderno", $orderNo)->find();
            if ($isSuccess) {

                if ($payResult == 1) {
                    if ($payType == 1) {
                        //处理表单
                        $order['merchantno'] = $merchantId;
                        $order['ordernocard'] = $mchtOrderId;
                        $order['bank'] = $issuerId;
                        $order['success'] = 1;
                        $res = db("account_capital")->where("id", $order['id'])->update($order);
                        if ($res) {
                            $this->assign("record", $post);
                            return $this->fetch("kltsuccess");
                        } else {
                            $this->assign("record", $post);
                            return $this->fetch("kltserver");
                        }
                    } else {
                        $order['merchantno'] = $merchantId;
                        $order['ordernocard'] = $orderNo;
                        $order['success'] = 2;
                        $res = db("account_capital")->where("id", $order['id'])->update($order);
                        return $this->fetch("kltfail");
                    }

                }
            } else {
                $order['merchantno'] = $merchantId;
                $order['ordernocard'] =$orderNo;
                $order['success'] = 2;
                $res = db("account_capital")->where("id", $order['id'])->update($order);
                return $this->fetch("kltfail");
            }
        }else{
            return $this->fetch("front/income/index");
        }
    }

    public function klt(){
        $interface = input("interface");
        $user = db("account_registration")->where("id",$this->userId)->find();
        $order = array();
        $order['orderno'] = 'No'.date("YmdHis").rand(10,100);
        $order['catid'] = 1;
        $order['lang'] = 'zh-cn';
        $order['username'] = $user['username'];
        $order['contact'] = $user['contact'];
        $order['mobile'] = $user['mobile'];
        $order['email'] = $user['email'];
        $order['amount'] = input('amount');
        $order['payment'] = $interface;
        $order['audit'] = 2;
        $order['onlinepay'] = 1;
        $order['success'] = 0;
        $order['createdate'] = date("YmdHis");
        $res = db("account_capital")->data($order)->insert();
        if($res){
            //生成订单成功，跳转支付页面
            $payment = db("pay_interface")->where("id",$interface)->find();
            $this->assign("payment",$payment);
            //开联通
            $request = Request::instance();
            $params = array();
            $params['inputCharset'] = "1";
            $params['pickupUrl'] = $request->domain().url('front/payform/kltok');
            $params['receiveUrl'] = $request->domain().url('front/payform/kltok');
            $params['version'] = "v1.0";
            $params['language'] = "1";
            $params["signType"] = "1";
            $params["merchantId"] = $payment["merchantno"];
            $params["orderNo"] = $order["orderno"];
            $params["orderAmount"] = floatval($order['amount'])*100;
            $params["orderCurrency"] = "156";
            $params["orderDatetime"] = $order['createdate'];
            $params["productName"] = config("productName");
            $params["productDesc"] = config("productDesc");
            $params["orderExpireDatetime"] = 60;
            $params["payType"] = "1";
            $signParams = "inputCharset=".$params['inputCharset']."&pickupUrl=".$params['pickupUrl']."&receiveUrl=".
                $params['receiveUrl']."&version=".$params['version']."&language=".$params['language']."&signType="
            .$params['signType']."&merchantId=".$params["merchantId"]."&orderNo=".$params['orderNo'].
                "&orderAmount=".$params['orderAmount']."&orderCurrency=".$params['orderCurrency']."&orderDatetime="
            .$params['orderDatetime']."&orderExpireDatetime=".$params["orderExpireDatetime"]."&productName="
            .$params['productName']."&productDesc=".$params['productDesc']."&payType=".$params['payType']."&key=ddddeiejtodjd53434";
            $this->assign("sign",$signParams);
            $signMsg = strtoupper(md5($signParams));
            $this->assign("params",$params);
            $this->assign("signMsg",$signMsg);
            return $this->fetch();
        }else{
            $this->error("入金操作失败，请重试！",url("front/personal/index"));
        }
    }

    public function ok(){
        $post = input();
        $this->assign("record",$post);
        return $this->fetch();
    }

    public function err(){
        $post = input();
        $this->assign("record",$post);
        return $this->fetch();
    }
}